<template>
  <div class="accurate-handout">
    <div v-if="!classData && Object.keys(directData).length === 0" class="noData">
      <div>
        <img src="/src/assets/one-prepare/no-data.png" alt="点津问道标品" width="475">
        <p>暂未添加讲义，请上传讲义或添加讲义</p>
        <el-button @click="uploadHandout">上传讲义</el-button>
        <el-button @click="addHandout">添加讲义</el-button>
      </div>
    </div>
    <div v-else class="haveData">
      <div class="left">
        <div class="difficult" v-if="classData">
          <div class="title">
            <span>重难点</span>
            <span class="edit" @click="editDifficult">编辑</span>
          </div>
          <div class="content" v-if="classData">
            <el-input
              type="textarea"
              resize="none"
              v-model="classData.difficultPoint"
              :placeholder="'暂未添加重难点,点击编辑按钮添加'"
              :disabled="isEdit" class="noDifficult"
              @keyup.enter="difficultSave"
              @blur="difficultSave"/>
          </div>
        </div>
        <div class="menu" v-if="!((classData && classData.child && classData.child.type === 1) || directType === 1)">
          <div class="title">讲义目录</div>
          <div class="content">
            <cus-empty v-if="!menuData.length"/>
            <div v-for="data in menuData" :key="data.id" class="handout-menu">
              <div v-if="data.type === 1">{{ data.content }}</div>
              <div v-else-if="data.type === 2">{{ removeHtml(data.content) }}</div>
              <div v-else-if="data.type === 3">
                <p class="menu-knowledge">{{ data.content }}</p>
                <div v-for="child in data.child" :key="child" class="child">
                  <span v-if="child.type === 1">{{ child.content }}</span>
                  <span v-if="child.type === 2">{{ removeHtml(child.content)}}</span>
                  <span v-else-if="child.type === 3" class="menu-knowledge-point">知识点{{ child.index }} {{ child.content }}</span>
                  <span v-else-if="child.type === 4" class="menu-question">例{{ child.index }}</span>
                </div>
              </div>
              <div v-else-if="data.type === 4"><span class="menu-question">例{{ data.index }}</span></div>
            </div>
          </div>
        </div>
      </div>
      <div class="right" :class="{ 'right_width' : !classData }">
        <template v-if="(classData && classData.child && classData.child.type === 1) || directType === 1">
          <iframe :src="`${basePath}${classData.child.path}`" frameborder="0" width="100%" height="100%" v-if="classData && classData.child"></iframe>
          <iframe :src="`${basePath}${previewPath}`" frameborder="0" width="100%" height="100%" v-else></iframe>
        </template>
        <template v-else>
          <HandoutPreviewComponent class-preview :handout="handoutId ? handoutId : classData.child.handoutId" :key="timer"/>
        </template>
      </div>
      <div class="btns">
        <div class="editHandout" @click="editHandout" v-if="(directType && directType !== 1) || (classData && classData.child.type !== 1)">
          <img src="/src/assets/one-prepare/edit.png" alt="">
        </div>
        <div class="preview" @click="preview" v-if="(directType && directType !== 1) || (classData && classData.child.type !== 1)"><i class="iconfont iconyulan"></i></div>
        <div class="download" @click="downLoadHandout" v-if="((directType && directType !== 1) || (classData && classData.child.type !== 1)) && prepareData.status === 3"><i class="iconfont iconxiazai"></i></div>
        <div class="download" @click="downLoad" v-if="((directType && directType === 1) || (classData && classData.child.type === 1)) && prepareData.status === 3">
        <i class="iconfont iconxiazai"></i></div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { computed, ref, onUnmounted } from 'vue'
import $ from '$'
import store from './../../store'
import HandoutPreviewComponent from '@/views/handout/index.vue';
import AddHandoutComponent from './../components/add-handout.vue';
import UploadHandoutComponent from './../components/upload-handout.vue'
import handoutStore from '@/views/handout/store/index'
import { ElMessage } from 'element-plus';
import downloadComponent from '@/views/database/components/download.vue'

export default {
  components: { HandoutPreviewComponent },
  setup () {
    let classData = computed(() => store.state.classData) //获取课次内容
    let directClass = computed(() => store.state.directClass) //是否直接备课
    let prepareData = computed(() => store.state.prepareData) //最外面列表页数据
    let menuData = computed(() => handoutStore.state.catalogData); //讲义目录数据
    let isEdit = ref(true)
    let directType = ref() //直接备课，讲义编辑或预览
    let isDirect = ref(false) //左侧重难点是否显示
    let directData: any = ref({})
    let basePath = $.utils.generatBasePath() + `furl=${import.meta.env.VITE_APP_BASE_URL}`;
    let removeHtml = computed(() => { return (data) => { return data.replace(/<[^>]+>/g,"").substr(0,10)} } )
    let previewPath = ref()
    const editDifficult = () => {
      isEdit.value = false
    }
    const directRequest = () => {
      //讲义是否与课次绑定
      $.http.post('/admin/teachTimesHandoutRelation/query', { indexId: prepareData.value.id}).then(res => {
        if (res.result && res.json.length) {
          directData.value = res.json[0]
          store.commit('set_direct_data', directData.value)
          handoutId.value = res.json[0].handoutId
          directType.value = res.json[0].type
          store.commit('set_direct_type', res.json[0].type)
          store.commit('set_handout_id', res.json[0].handoutId)
          store.commit('set_direct_class', false)
          res.json[0].type === 1 && $.http.post('/admin/material/queryById', { id: handoutId.value}).then((result) => {
            result.result && (previewPath.value = result.json.filePath)
            store.commit('set_file_path', result.json.filePath)
          })
        }
      })
    }
    setTimeout(() => {
      !classData.value && directRequest()
      classData.value && (store.commit('set_direct_class',false))
      $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 }) //当前备课到第几步 点击编辑后变为第二步 无法退回到第一步
      classData.value && $.http.post('/admin/lessonTimes/saveOrUpdate', { id: classData.value.id, checked: 1, lessonThirdId: prepareData.value.thirdId }) //更新已备课 checked：1 已选中课次
    })

    const difficultSave = () => {
      let params = {
        id: classData.value.id,
        difficultPoint: classData.value.difficultPoint,
      }
      $.http.post('/admin/lessonTimes/saveOrUpdate', params)
    }
    let handoutId = ref('')
    let subjectId = ref()
    $.emitter.emit('effect', (id) => subjectId.value = id)
    const editHandout = () => {
      let jumpHandoutId, type, indexId
      if (classData.value) {
        jumpHandoutId = classData.value.child.handoutId
        type = classData.value.child.type
        indexId = classData.value.id
      } else {
        jumpHandoutId = directData.value.handoutId
        type = directData.value.type
        indexId = prepareData.value.id
      }
      if ((directData.value && directData.value.copyHandout === 1) || (classData.value && classData.value.child && classData.value.child.copyHandout === 1)) {
        window.open(`/#/handout/false/${jumpHandoutId}/${subjectId.value}`)
      } else if ((directData.value && directData.value.copyHandout !== 1) || (classData.value.child && classData.value.child.copyHandout !== 1)) {
        $.http.post('/admin/handoutNode/copyHandout',{ handoutId: jumpHandoutId }).then(res => {
          if (res.result) {
            handoutId.value = res.json;
            timer.value = new Date().getTime()
            store.commit('set_handout_id', res.json)
            store.commit('set_direct_class', false)
            $.http.post('/admin/teachTimesHandoutRelation/updateByIndexId', { indexId: indexId, handoutId: res.json, tpye: type, copyHandout: 1 }) //更新课次, copyHandout:1为已复制
            window.open(`/#/handout/false/${res.json}/${subjectId.value}`)
            if (classData.value) {
              $.emitter.emit('standard-init', true)
            } else {
              directRequest()
            }
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    }
    const preview = () => {
      let jumpHandoutId
      if (classData.value) {
        jumpHandoutId = classData.value.child.handoutId
      } else {
        jumpHandoutId = directData.value.handoutId
      }
      window.open(`/#/handout/true/${jumpHandoutId}/${subjectId.value}`)
    }
    const uploadHandout = async() => {
      $.modal.create({title:'上传讲义', width: 550, zIndex: 2016, component: UploadHandoutComponent }).then(res => {
        res && (directType.value = 1, previewPath.value = res.json.filePath)
        $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 })
        $.http.post('/admin/teachTimesHandoutRelation/saveOrUpdate', { indexId: prepareData.value.id, type: 1, handoutId: res.json.id }).then(result => {
          result.result && directRequest()
        })
      })
    }

    const addHandout = async () => {
      let title = '添加标准讲义';
      $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 })
      let result = await $.drawer.create({ title, width: 1080, zIndex: 2016, component: AddHandoutComponent });
      result && (directType.value = result.filePath ? 1 : 2)
      let res = await $.http.post('/admin/teachTimesHandoutRelation/saveOrUpdate', { indexId: prepareData.value.id, type: result.filePath ? 1 : 2, handoutId: result.id });
      res.result && directRequest()
      $.utils.message(res.result, title);
      $.http.post('/admin/lessonInfo/saveOrUpdate', { id: prepareData.value.id, step: 2 }) //当前备课到第几步 点击编辑后变为第二步 无法退回到第一步
    }

    const downLoad = () => {
      let jumpHandoutId
      if (classData.value) {
        jumpHandoutId = classData.value.child.handoutId
      } else {
        jumpHandoutId = directData.value.handoutId
      }
      $.http.post('/admin/material/queryById', {id: jumpHandoutId}).then((res) => {
        if (res.result && res.json) {
          $.element('a', {attrs: {href: `${import.meta.env.VITE_APP_BASE_URL}${res.json.filePath}`, download: `${res.json.fileName}.${res.json.ext}`}}).click();
        }
      })
    }
    const downLoadHandout = () => {
      let jumpHandoutId
      if (classData.value) {
        jumpHandoutId = classData.value.child.handoutId
      } else {
        jumpHandoutId = directData.value.handoutId
      }
      $.modal.create({
        title: '下载讲义',
        width: 640,
        component: downloadComponent
      }).then((res: any) => {
        window.open(`${import.meta.env.VITE_APP_BASE_URL}/admin/material/down?materialId=${ jumpHandoutId }&fileType=${ res.fileType }&type=${ res.type }`);
      });
    }
    let timer = ref()
    let handoutRef = ref()
    const __postMessageFn = event => {
      if (event.origin === window.location.origin && event.data.type === 'handout-save-success') {
        timer.value = new Date().getTime()
        // handoutRef.value.init()
      }
    };
    window.addEventListener('message', __postMessageFn);
    onUnmounted(() => window.removeEventListener('message', __postMessageFn));
    return {
      classData, editDifficult, isEdit, difficultSave, editHandout, handoutId, subjectId, directRequest, directData, removeHtml, timer, handoutRef,
      preview, directClass, uploadHandout, addHandout, prepareData, directType, isDirect, basePath, previewPath, downLoad, downLoadHandout, menuData
     }
  }
}
</script>
<style lang="scss" scoped>
  :deep(.el-textarea__inner) {
    border: none;
    padding: 0;
  }
  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    background: #fff;
    color: inherit;
  }
  .menu-question {
    margin: 0 15px 10px 0;
    height: 25px;
    padding: 3px 8px;
    line-height: 25px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    transition: all .25s;
    cursor: pointer;
    max-width: 200px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .accurate-handout {
    display: flex;
    .noData {
      display: flex;
      text-align: center;
      width: 475px;
      margin: 0 auto;
      button {
        margin-top: 40px;
        color: #72b22a;
        border: 1px solid #72b22a;
        &:hover {
          color: #fff;
          background: #72b22a;
        }
      }
    }
    .haveData {
      display: flex;
      width: 100%;
    }
    .left {
      padding: 0px 20px 15px 0;
      .difficult {
        width: 230px;
        border-radius: 4px;
        overflow: hidden;
        border: solid 1px #72b22a;
        .title {
          color: #fff;
          background: #72b22a;
          display: flex;
          align-items: center;
          padding: 5px 10px;
          .edit {
            margin-left: auto;
            font-size: 12px;
            cursor: pointer;
          }
        }
        .content {
          padding: 17px 20px;
          display: flex;
          flex-wrap: wrap;
          .noDifficult {
            color: #999999;
            font-size: 12px;
          }
          textarea {
            border: none;
            outline: none;
          }
        }
      }
      .menu {
        margin-top: 20px;
        width: 230px;
        border-radius: 4px;
        overflow: hidden;
        border: solid 1px #DEE4F1;
        height: calc(100% - 100px);
        .title {
          color: #fff;
          background: #72b22a;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 5px 10px;
        }
        .content {
          height: 100%;
          overflow: auto;
          .handout-menu {
            background: #F5F7FA;
            margin-top: 10px;
            border-radius: 4px;
            padding: 5px 10px;
            .child {
              & > span {
                line-height: 30px;
              }
            }
            .menu-knowledge {
              color: $--color-primary;
            }
            .menu-knowledge-point {
              color: $--color-remind;
            }
          }
        }
      }
    }
    .right {
      width: 758px;
      background: #FFFFFF;
      position: relative;
      height: 100%;
      overflow: auto;
      & > div {
        & > div {
          height: 100%;
          overflow: auto;
          background: #FFFFFF;
          & > div {
            background: #FFFFFF;
          }
        }
      }
    }
    .btns {
      display: flex;
      flex-direction: column;
      .editHandout, .preview, .download {
        background: #fff;
        border: 1px solid #E4E7ED;
        width: 40px;
        height: 40px;
        border-radius: 0 6px 6px 0;
        cursor: pointer;
        text-align: center;
        line-height: 38px;
        &:nth-of-type(2), &:nth-of-type(3) {
          margin-top: 10px;
        }
      }
    }
    .right_width {
      width: 880px;
      margin-left: 60px;
    }
  }
</style>
